const CryptoJs = require('crypto-js')
const HmacMD5 = CryptoJs.HmacMD5
const AES = CryptoJs.AES
const Latin1 = CryptoJs.enc.Latin1
const mode = CryptoJs.mode.CBC
const padding = CryptoJs.pad.ZeroPadding

export default {
  install(Vue) {
    Vue.prototype.$auth = {
      token: function(url, username, password) {
        let path = `${url}:${new Date().getTime()}`
        if (username && password) {
          return `${username}:${this.aesEncrypt(this.encrypt(password), path)}`
        }

        let user = uni.getStorageSync('user')
        if (user.username && user.password) {
          return `${user.username}:${this.aesEncrypt(user.password, path)}`
        }

        return null
      },


      encrypt: function(password) {
        return HmacMD5(password, password).toString()
      },

      aesEncrypt(password, msg, iValue = 'O2%=!ExPCuY6SKX(') {
        let message = Latin1.parse(msg)
        let key = Latin1.parse(password)
        let iv = Latin1.parse(iValue)
        return AES.encrypt(message, key, {
          iv: iv,
          mode: mode,
          padding: padding
        }).toString()
      },
      aesDecrypt(password, ciphertext, iValue = 'O2%=!ExPCuY6SKX(') {
        let key = Latin1.parse(password)
        let iv = Latin1.parse(iValue)
        return AES.decrypt(ciphertext, key, {
          iv: iv,
          mode: mode,
          padding: padding
        }).toString()
      },


      logIn(username, password, data) {
        uni.setStorageSync('user', {
          username,
          password: this.encrypt(password),
          data
        })
      },
      logOut() {
        uni.removeStorageSync('user')
      },
      isLogin() {
        let user = uni.getStorageSync('user')
        if (!!user) {
          return user
        } else {
          return false
        }
      },
    }
  }
}
